package cn.yuanqiao.common.config;

import cn.yuanqiao.common.enums.DbIdEnum;
import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

@Component
public class YqDatabaseIdProvider implements DatabaseIdProvider {

    @Autowired
    private DataSource dataSource;

    @Override
    public void setProperties(Properties p) {
    }

    @Override
    public String getDatabaseId(DataSource dataSource) throws SQLException {
        Connection connection = null;
        try{
            connection = dataSource.getConnection();
            String url = connection.getMetaData().getURL();
            if (url.contains(DbIdEnum.ORACLE.getName())) {
                return DbIdEnum.ORACLE.getCode();
            } else if (url.contains(DbIdEnum.PG_SQL.getName())) {
                return DbIdEnum.PG_SQL.getCode();
            } else if (url.contains(DbIdEnum.MS_SQL.getName())) {
                return DbIdEnum.MS_SQL.getCode();
            } else if (url.contains(DbIdEnum.KINGBASE.getName())) {
                return DbIdEnum.KINGBASE.getCode();
            }else if (url.contains(DbIdEnum.DM.getName())) {
                return DbIdEnum.DM.getCode();
            }else if (url.contains(DbIdEnum.OSCAR.getName())) {
                return DbIdEnum.OSCAR.getCode();
            }else if (url.contains(DbIdEnum.OPEN_GAUSS.getName())){
                return DbIdEnum.OPEN_GAUSS.getCode();
            }else {
                return DbIdEnum.MYSQL.getCode();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(connection!=null){
                connection.close();
            }
        }
        return null;
    }

    public String getDatabaseId(){
        String databaseId = "default";
        try {
            databaseId = getDatabaseId(dataSource);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return databaseId;
    }
}
